<template>
  <div style="padding-bottom: 20px">
    <div class="df">
      <h2>
        退货申请单
        <span style="margin-left: 20px; color: #200281">{{
          Send.refundBatchNo
        }}</span>
      </h2>
    </div>
    <div style="width: 100%; border-bottom: 1px solid #000">
      <h2>
        <i class="el-icon-document"></i><span style="margin-left: 20px; font-weight: normal">退货药品清单</span>
      </h2>
    </div>
    <el-row :span="6" class="df" style="margin: 20px 0">
      <el-col :span="6" style="display: flex; align-items: center">
        <span style="display: block; margin-right: 10px; width: 80px">配送企业:</span>
        <el-input v-model="Send.companyName" size="mini" placeholder="请选择" @change="instChange" disabled>
        </el-input>
      </el-col>
    </el-row>
    <el-alert size="mini" show-icon style="
        background-color: #d3deee;
        border: 1px solid #2558ac;
        color: #2558ac;
        font-size: 14px;
      ">
      退货药品种类总数
      <span class="number">{{ tableData.length }}</span> 项，总金额<span class="number">{{ this.Send.totalFee }}</span>元。
    </el-alert>
    <el-table :data="tableData2" style="width: 100%; margin-top: 20px" size="mini">
      <el-table-column prop="batchName" label="集采批次" width="180">
      </el-table-column>
      <el-table-column prop="medicineNo" label="流水号" width="180">
      </el-table-column>
      <el-table-column prop="medicineName" label="通用名" width="180">
      </el-table-column>
      <el-table-column prop="categoryName" label="品种名称"> </el-table-column>
      <el-table-column label="采购数量">
        <template slot-scope="scope">
          {{ scope.row.purchaseAmount }}
        </template>
      </el-table-column>
      <el-table-column prop="purchasePrice" label="采购价(元)">
      </el-table-column>
      <el-table-column prop="purchaseFee" label="采购金额(元)">
      </el-table-column>
      <el-table-column label="结算发票代码">
        <template slot-scope="scope">
          {{ Send.invoiceNo }}
        </template>
      </el-table-column>
      <el-table-column label="退货计量单位" prop="chargeUnit">
      </el-table-column>
      <el-table-column label="退货数量" prop="amount"> </el-table-column>
      <el-table-column prop="fee" label="退货金额(元)"> </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="primary" slot="reference" size="mini" @click="toAdd(scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block" style="margin: 20px 0; margin-left: 60%">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="totalSize" :page-sizes="[20, 30, 40, 50]">
      </el-pagination>
    </div>
    <div style="display: flex; align-items: center; margin-bottom: 20px">
      <span style="width: 80px">退货原因:</span><el-input v-model="this.Send.refundReason" size="mini" style="width: 25%" disabled></el-input>
    </div>
    <div style="display: flex; align-items: center; margin-bottom: 20px">
      <span style="margin-right: 20px">原因附件:</span><a :href="this.Send.explainFile">退货清单盖章扫描件.pdf</a>
    </div>

    <h2 style="
        text-align: left;
        padding-bottom: 20px;
        border-bottom: 1px solid #000;
        margin-top: 20px;
      ">
      <i class="el-icon-document"></i><span style="margin-left: 20px; font-weight: normal">退货确认信息</span>
    </h2>
    <!-- 同意退货或者不同意退货 -->
    <div v-if="Send.status === 1||Send.status === 6||Send.status === 7">
      <div style="margin-bottom: 20px;"><span style="margin-right: 20px;">退货操作：</span>
        <el-radio v-model="isAgreeReturn" :label="1" :disabled="Send.status==6||Send.status === 7">同意退货</el-radio>
        <el-radio v-model="isAgreeReturn" :label="2" :disabled="Send.status==6||Send.status === 7">不同意退货</el-radio>
      </div>
      <div style=" display: flex; margin-bottom: 60px;" v-if="isAgreeReturn === 1">
        <div>
          <div class="flex" style="margin-top:8px">
            <span style="margin-right: 20px;">退货票据：</span>
            <uploadFile v-model="params.returnBillList" />
          </div>
        </div>
        <div style="display: flex;margin-left: 40px;margin-right: 20px;">
          <div style="margin-top: 7px;">
            <div class="align-center">
              <span style="margin-right: 20px;">销项负数发票：</span>
            </div>
          </div>
        </div>
        <div>
          <div class="flex" style="margin-bottom:12px" v-for="(item, i) in studentList" :key="i">
            <uploadFile v-model="item.returnBillList" />
            <el-input v-model="studentList[i].value" style="width: 160px;margin-right: 20px;margin-left: 12px;" size="mini"></el-input>
            <div v-if="Send.status === 1">
              <el-button size="mini" circle icon="el-icon-plus" @click="addList()"></el-button>
              <el-button size="mini" circle icon="el-icon-minus" @click="subList(i)" v-if="i > 0"></el-button>
            </div>
          </div>
        </div>
      </div>
      <div style="display: flex;align-items: center;position: relative;margin-top: 15px;" v-else-if="isAgreeReturn === 2">
        <div style="display: flex;align-items: center;margin-right: 20px;"><span style="margin-right: 20px;">不同意退货原因附件：</span>
          <uploadFile v-model="params.notAgreeReturnReasonFile" />
        </div>
      </div>
      <!-- <div style="display: flex;align-items: center;position: relative;" v-else-if="isAgreeReturn === 2">
        <div style="display: flex;align-items: center;margin-right: 20px;position: absolute;left: 0;margin-top: 0;" v-if="userInfo.role_name.includes('distribution')"><span style="margin-right: 20px;">不同意退货原因附件：</span>
          <el-upload :action="fileUrl()" :on-success="handleUploadSuccess1">
            <el-button size="small" type="primary">上传文件</el-button>
          </el-upload>
        </div>
      </div> -->
      <div class="justify-align-center">
        <el-button v-if="Send.status === 1" class="width" @click="handleTop(isAgreeReturn)" style="margin-right:60px;" slot="reference" type="primary" size="small">提交</el-button>
        <el-button v-if="Send.status === 3 || Send.status === 6" class="width" @click="handleTop(4)" style="margin-right:60px;" slot="reference" type="primary" size="small">确认收货</el-button>
        <el-button v-if="Send.status === 7" class="width" size="small" @click="cancelReturn" type="info">撤销</el-button>
        <el-button class="width" size="small" @click="closeDialog">取消</el-button>
      </div>
    </div>
    <div v-if="Send.status === 3 ||Send.status === 4">
      <div style=" display: flex; margin-bottom: 60px;" v-if="isAgreeReturn === 1">
        <div>
          <div class="flex" style="margin-top:8px">
            <span style="margin-right: 20px;">退货票据：</span>
            <a :href="this.Send.refundProofFile">{{this.Send.refundProofNo}}</a>
          </div>
        </div>
        <div style="display: flex;margin-left: 40px;margin-right: 20px;">
          <div style="margin-top: 7px;">
            <div class="align-center">
              <span style="margin-right: 20px;">销项负数发票：</span>
            </div>
          </div>
        </div>
        <div>
          <div class="flex" style=" margin-bottom:12px;display: flex;align-items: center;" v-for="(item, i) in returnList" :key="i">
            <a :href="item.negativeInvoiceFile" style="margin-right: 20px;display: block;width:fit-content;min-width: 150px;max-width: 500px;">销项发票{{ item.negativeInvoiceNo }}.pdf</a>
            <el-input v-model="item.negativeInvoiceNo" disabled></el-input>
          </div>
        </div>
      </div>
      <div class="justify-align-center">
        <el-button v-if="Send.status === 1" class="width" @click="handleTop(isAgreeReturn)" style="margin-right:60px;" slot="reference" type="primary" size="small">提交</el-button>
        <el-button v-if="Send.status === 3 || Send.status === 6" class="width" @click="handleTop(4)" style="margin-right:60px;" slot="reference" type="primary" size="small">确认已发货</el-button>
        <el-button v-if="Send.status === 7" class="width" size="small" @click="cancelReturn" type="info">撤销</el-button>
        <el-button v-if="Send.status!==4" class="width" size="small" @click="closeDialog">取消</el-button>
      </div>
    </div>
    <div v-if="Send.status === 4">
      <h2 style="
        text-align: left;
        padding-bottom: 20px;
        border-bottom: 1px solid #000;
        margin-top: 20px;
      ">
        <i class="el-icon-document"></i><span style="margin-left: 20px; font-weight: normal">退货入库信息</span>
      </h2>
      <div style="
          display: flex;
          align-items: center;
          margin-right: 20px;
          margin-bottom: 40px;
        ">
        <span style="color: red">*</span>
        <span style="margin-right: 20px">验收入库单:</span>
        <uploadFile v-model="params.treasuryList" />
      </div>
      <el-button @click="handleTop(5)" class="width" style="margin-right: 60px; margin-left: 40%" slot="reference" type="primary" size="small">确认验收入库</el-button>
      <el-button class="width" size="small" @click="hide">取消</el-button>
    </div>
    <div v-else-if="Send.status === 2">
      <div style="display: flex;align-items: center;margin-right: 20px;margin-bottom: 40px;"><span style="margin-right: 20px;">不同意退货原因附件：</span><a :href="this.Send.rejectReasonFile">关于不同意退货的说明.pdf</a></div>

      <div class="justify-center" v-if="!Send.areaInvolveStatus || Send.areaInvolveStatus == 0">
        <el-button class="width" style="margin-right:60px;" slot="reference" type="primary" size="small" @click="handleTop(0)">确认已发货</el-button>
        <el-button type="info" style="margin-right:60px;" class="width" size="small" @click="toHealthInsuranceBureau">医保局介入</el-button>
        <el-button class="width" size="small" @click="closeDialog">取消</el-button>
      </div>
      <div v-else-if="Send.areaInvolveStatus == 1">
        <h2 style="
          text-align: left;
          padding-bottom: 20px;
          border-bottom: 1px solid #000;
          margin-top: 20px;
        ">
          <i class="el-icon-document"></i><span style="margin-left: 20px; font-weight: normal">医保局介入</span>
        </h2>
        <div style="
          display: flex;
          align-items: center;
          margin-right: 20px;
          margin-bottom: 40px;
        ">
          <span style="margin-right: 20px">处理选项：</span>
          <el-radio v-model="isAgreeInsurance" :label="1">确认通过</el-radio>
          <el-radio v-model="isAgreeInsurance" :label="2">确认不通过</el-radio>
        </div>
        <el-button class="width" @click="handleTop(6)" style="margin-right: 60px; margin-left: 40%" slot="reference" type="primary" size="small">提交</el-button>
        <el-button class="width" size="small" @click="closeDialog">取消</el-button>
      </div>
    </div>
    <el-dialog v-if="dialogVisible" title="退货药品信息" :width="dialogScreen ? '' : '1000px'" :visible.sync="dialogVisible" append-to-body>
      <AddReturns :instName="instData" addEdit="view" :returnTableInfo="addData" :flag2="dialogVisible" @chooseData="changeData" @changeTwo="changeDia">
      </AddReturns>
    </el-dialog>
  </div>
</template>

<script>
import {
  update,
  NegativeAll,
  getDetail, NegativeItemList, removeMaster
} from "../../api/businessTwo/orderRefund";
import { getToken } from "@/util/auth";
import { mapGetters } from 'vuex'
import AddReturns from "../../components/orderRefund/AddReturns.vue"
import uploadFile from '@/components/uploadFile/uploadFile.vue'
export default {
  components: {
    AddReturns,
    uploadFile,
  },
  props: {
    Send: {
      type: Object,
    },
    flag: {
      type: Boolean,
    },
  },
  data () {
    return {
      isAgreeInsurance: 1,
      params: {
        returnBillList: [],
        notAgreeReturnReasonFile: [],
        treasuryList: []
      },
      isAgreeReturn: 1,
      log () {
        console.log(this.radio);
      },
      studentList: [
        { returnBillList: [], value: '' }
      ],
      returnList: [],
      radio1: '',
      radio: '',
      value5: '',
      falseUpload: '',
      options: [{ label: "同上", value: '', value1: 0 }],
      instData: {},
      dialogScreen: false,
      cities: [],
      dialogVisible: false,
      addData: {},
      pageSize: 10,
      tableData1: [],
      totalSize: 0,
      form1: null,
      value2: null,
      value3: "",
      value4: "",
      num: 0,
      priceSum: 0,
      currentPage: 1,
      value: "",
      uploadUrl: "",
      form: [],
      dataIf: false,
      tableData: [],
      tableData2: [],
    };
  },
  created () {
    this.getList();

    this.logss()
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  watch: {
    value (val) {
      this.inputValue = val;
    },
  },
  methods: {
    closeDialog () {
      this.$emit("closeDialog");
    },
    //加号
    addList () {
      this.studentList.push({ returnBillList: [], age: '' })
    },
    //减号
    subList (index) {
      this.studentList.splice(index, 1);
    },
    async logss () {
      let res = await NegativeItemList({
        refundBatchId: this.Send.id,
        refundBatchNo: this.Send.refundBatchNo
      })
      this.returnList = res.data.data
      console.log(this.returnList);

    },
    productSelect (e) {
      let value = e.target.value; // 输入框值
      if (value) {
        // 你输入才有这个值 不为空，如果你下拉框选择的话 这个值为空
        this.value4 = value;
        /*  this.options[0].value=value */
      }
      console.log(this.options);
      console.log(e, this.tableData);
    },
    handleUploadSuccess (response, row) {
      // 处理上传成功后的响应数据
      console.log("上传成功！", response);
      // 保存返回结果到某个变量
      console.log(row);
    },
    handleUploadSuccess1 (response, row, i) {
      // 处理上传成功后的响应数据
      console.log("上传成功！", response);
      // 保存返回结果到某个变量
      this.studentList[i].uploadUrl = response.data.name;
      console.log(row);
    },
    toAdd (data) {
      this.addData = data
      this.dialogVisible = true
    },
    changeTabel () {
      this.tableData2 = this.tableData.slice((this.currentPage - 1) * this.pageSize,
        this.currentPage * this.pageSize)
    },
    async getList () {
      let res = await getDetail({
        current: this.currentPage,
        size: this.pageSize,
        refundBatchNo: this.Send.refundBatchNo,
        instName: this.instName,
      });
      this.dataIf = res.data.data.haveBill;
      console.log(this.dataIf);
      this.tableData = res.data.data.orderRefundVOS;
      this.tableData2 = this.tableData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
      this.totalSize = res.data.data.orderRefundVOS.length;
      // this.number();
    },
    handleTop (data) {
      if (data == 0) {
        update({
          status: data,
          id: this.Send.id,
        }).then(() => {
          this.$message.success("确认已发货成功");
          this.hide();
        });
      }
      if (data == 2) {
        if (!this.params.notAgreeReturnReasonFile.length) {
          console.log(1124);
          this.$message.error("请填写不同意退货原因附件");
        } else {
          console.log(11);
          console.log(this.params);
          update({
            status: 2,
            rejectReasonFile: this.params.notAgreeReturnReasonFile[0].negativeInvoiceFile,
            id: this.Send.id,
          }).then(() => {
            this.$message.success("提交成功");
            this.hide();
          });
        }
      } else if (data == 1) { // 同意退货 分两种
        console.log(this.dataIf);
        console.log('%c [ this.studentList ]-377', 'font-size:13px; background:#fe4ebd; color:#ff92ff;', this.studentList)
        if (this.dataIf) {
          let isValueNull = this.studentList.some(item => {
            return item.value === null || item.value === undefined || item.value === '' || !item.value
          })
          console.log(isValueNull);
          if (isValueNull) {
            return this.$message.warning('请输入票据号码！')
          }
          let isFileNull = this.studentList.some(item => {
            return item.returnBillList.length === 0
          })
          if (isFileNull) {
            return this.$message.warning('请上传票据文件！')
          }
          if (this.params.returnBillList.length == 0) {
            return this.$message.warning('请上传退货票据！')
          }
          console.log(123);
          console.log(this.params);
          let arr = []
          this.studentList.map((v) => {
            arr.push({
              refundBatchId: this.Send.id,
              refundBatchNo: this.Send.refundBatchNo,
              negativeInvoiceNo: v.value,
              negativeInvoiceFile: v.returnBillList[0].negativeInvoiceFile
            })
          })
          console.log(arr);
          update({
            refundProofFile: this.params.returnBillList[0].negativeInvoiceFile, //退货票据
            refundProofNo: this.params.returnBillList[0].name,
            status: 3,
            id: this.Send.id,
          }).then(() => {
            NegativeAll(arr).then(() => {
              this.$message.success("提交成功");
              this.hide();
            });
          });
        } else {
          update({
            refundProofFile: this.params.returnBillList[0].negativeInvoiceFile || null,
            status: 3,
            id: this.Send.id,
          }).then(() => {
            let arr = []
            this.studentList.map((v) => {
              arr.push({
                refundBatchId: this.Send.id,
                refundBatchNo: this.Send.refundBatchNo,
                negativeInvoiceNo: v.value,
                negativeInvoiceFile: v.returnBillList[0].negativeInvoiceFile
              })
            })
            NegativeAll(arr).then(() => {
              this.$message.success("提交成功");
              this.hide();
            });
          });
        }
      } else if (data === 4) {
        update({
          status: 4,
          id: this.Send.id,
        }).then(() => {
          this.$message.success("提交成功");
          this.hide();
        });
      } else if (data === 5) {
        if (this.params.treasuryList.length == 0) {
          this.$message.error("请上传验收入库单");
        } else {
          update({
            stockFile: this.params.treasuryList[0].negativeInvoiceFile,
            status: 5,
            id: this.Send.id,
          }).then(() => {
            this.$message.success("提交成功");
            this.hide();
          });
        }

      } else if (data === 6) {
        let status
        if (this.isAgreeInsurance == 1) {
          status = 6
        } else if (this.isAgreeInsurance == 2) {
          status = 7
        }
        update({
          status: status,
          id: this.Send.id,
        }).then(() => {
          this.$message.success("提交成功");
          this.hide();
        });
      }
    },
    cancelReturn () {
      removeMaster(this.Send.id).then(() => {
        this.$message.success("撤销成功")
        this.hide()
      })
    },
    toHealthInsuranceBureau () {
      update({
        status: 2,
        id: this.Send.id,
        areaInvolveStatus: 1
      }).then(() => {
        this.$message.success("提交成功");
        this.hide();
      });
    },
    instChange (data) {
      console.log(this.value3, data);
      if (!this.Send.instName) {
        this.instData.value = this.value3;

        this.form.map((v) => {
          if (this.value3 == v.value) {
            this.instData.label = v.label;
          }
          console.log(this.instData);
        });
      }
    },
    number () {
      this.priceSum = 0;
      this.num = this.tableData.length;
      this.tableData.forEach((v) => {
        if (v.purchaseFee === null) {
          v.purchaseFee = 0;
        }
        this.priceSum += parseFloat(v.purchaseFee);
      });
    },
    changeDia (data) {
      this.dialogVisible = data;
    },
    fileUrl () {
      return `/api/blade-resource/oss/endpoint/put-file?${this.website.tokenHeader
        }=${getToken()}`;
    },
    changeData () { },
    handleCurrentChange (val) {
      this.currentPage = val;
      // this.getList();
      this.changeTabel();
    },
    handleSizeChange (val) {
      this.pageSize = val;
      let pageTotal = Math.ceil(this.tableData.length / this.pageSize)
      if (pageTotal < this.currentPage) {
        this.currentPage = pageTotal
      }
      // this.getList();
      this.changeTabel();

    },
    hide () {
      this.$emit("changeSure", false);
    },
  },
};
</script>

<style lang="scss" scoped>
.df {
  display: flex;
  align-items: center;
}

.jcsb {
  justify-content: space-between;
}

.el-table {
  margin-bottom: 30px;
}
::v-deep .el-alert {
  padding: 4px 16px !important;
}
::v-deep .el-alert__icon.is-big {
  font-size: 22px !important;
}
::v-deep .el-alert__description {
  margin: 0;
}

.ml {
  margin-left: 60px;
}

::v-deep th {
  background-color: #f1f1f1;
}

::v-deep .el-table__cell {
  height: 50px !important;
}

h2 {
  font-size: 18px;
}

.width {
  width: 120px;
  height: 36px;
}

h2 {
  font-size: 14px;
}

.ret {
  margin-left: 30%;
  margin-right: 60px;
}

.number {
  font-size: 16px;
  color: #2558ac;
}

::v-deep th.el-table__cell {
  background-color: #fafafa;
}

::v-deep .el-table__cell {
  border-right: 1px solid #ebeef5 !important;
  text-align: center;
}

::v-deep .cell {
  display: flex;
  justify-content: center;
}
</style>
